package com.cx.controller;

import com.cx.common.ApiReturn;
import com.cx.pojo.*;
import com.cx.service.*;
import com.cx.util.QiniuCloudUtil;
import com.cx.util.WangEditor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("post")
public class PostController {
    @Autowired
    PostService postService;
    @Autowired
    PostTestService postTestService;
    @Autowired
    PraiseService praiseService;
    @Autowired
    UserCenterService userCenterService;


    @RequestMapping("selectByUserId")
    @ResponseBody
    public List<Post> selectByUserId(Integer userId){
        List<Post> posts = postService.selectByUserId(userId);
        return posts;
    }


    @RequestMapping("selectByUserName")
    @ResponseBody
    public List<Post> selectByUserName(String userName){
        List<Post> posts = postService.selectByUserName(userName);
        return posts;
    }

    @RequestMapping("selectByUserNameInPosttest")
    @ResponseBody
    public List<Posttest> selectByUserNameInPosttest(String userName){
        List<Posttest> posttests = postTestService.selectByUserNameByPostTest(userName);
        return posttests;
    }



//    @RequestMapping("selectByDianZan")
//    @ResponseBody
//    public List<Post> selectByDianZan(String userName){
//
//        praiseService.selectPostByUserName()
//
//        List<Post> posts = postService.selectByUserName(userName);
//        return posts;
//    }

    @RequestMapping("selectByPostId")
    @ResponseBody
    public Post selectByPostId(String postId,HttpSession session){

        Integer id = Integer.valueOf(postId);
        System.out.println(id);
        List<Post> posts = postService.selectByPostId(id);
        session.setAttribute("postId",postId);
        return posts.get(0);
    }

    @RequestMapping("selectByPostTestId")
    @ResponseBody
    public Posttest selectByPostTestId(String postId ){
        Integer id = Integer.valueOf(postId);
        System.out.println(id);
        Posttest posttest = postTestService.selectByPostTestId(id);
        return posttest;
    }

    @RequestMapping("selectByCarId")
    @ResponseBody
    public List<Post> selectByCarId(Integer carId){
        List<Post> posts = postService.selectByCarId(carId);
        return posts;
    }

    @RequestMapping("selectAll")
    @ResponseBody
    public List<Post> selectAll(){
        List<Post> posts = postService.selectAll();
        return posts;
    }

    @RequestMapping("selectByStatus")
    @ResponseBody
    public Integer selectByStatus(){
        Integer amount = postService.selectByStatus();
        return amount;
    }


    @RequestMapping("selectByStatusNum")
    @ResponseBody
    public List<Post> selectByStatusNum(){
        List<Post> posts = postService.selectByStatusNum(1);
        return posts;
    }

    @RequestMapping("selectPhoto")
    @ResponseBody
    public List<Post> selectPhoto(){
        List<Post> posts = postService.selectPhoto();
        System.out.println(posts.size());
//        Integer[] num = new Integer[5];
        Integer[] num = getNumArray(5,posts.size());
        List<Post> posts1 = new ArrayList<>();
        for (int i = 0; i < num.length; i++){
            posts1.add(posts.get(num[i]));
        }
        System.out.println(posts1.get(1).getPostName());
        return posts1;
    }


    // 获取一个长度为5的随机数
    public Integer[] getNumArray(int a,int b) {
        Integer[] num = new Integer[a];
        Random r = new Random();
        for (int i = 0; i < a;) {
            int temp = r.nextInt(b);
            if (!Arrays.asList(num).contains(temp)) {
                num[i] = temp;
                i++;
            }
        }
        return num;
    }



    @RequestMapping("selectAllPostTest")
    @ResponseBody
    public List<Posttest> selectAllPostTest(){
        List<Posttest> posttests = postTestService.selectAllPostTest();
        return posttests;
    }

    @RequestMapping("selectAllBrandName")
    @ResponseBody
    public List<Brand> selectAllBrandName(){
        List<Brand> brands = postService.selectAllBrandName();
        return brands;
    }


    @RequestMapping("selectByPostType")
    @ResponseBody
    public List<Post> selectByPostType(String postType){
        System.out.println(postType);
        if (postType.equals("不限")){
            List<Post> posts = postService.selectAll();
            return posts;
        }else {
            List<Post> posts = postService.selectByPostType(postType);
            return posts;
        }

    }

    @RequestMapping("selectByPostName")
    @ResponseBody
    public List<Post> selectByPostName(String postName){
        List<Post> posts = postService.selectByPostName(postName);
        return posts;
    }


    @RequestMapping("selectByPostTestName")
    @ResponseBody
    public List<Posttest> selectByPostTestName(String postName){
        List<Posttest> posttests = postTestService.selectByPostTestName(postName);
        return posttests;
    }

    @RequestMapping("selectByPostTime")
    @ResponseBody
    public List<Post> selectByPostTime(String postTime){
        System.out.println(postTime);
        if (postTime.equals("不限")){
            List<Post> posts = postService.selectAll();
            return posts;
        }else if (postTime.equals("2020")){
            String startTime = "2019-12-31";
            String endTime = "2021-1-1";
            List<Post> posts = postService.selectByPostTime(startTime,endTime);
            return posts;
        }else if (postTime.equals("2019")){
            String startTime = "2018-12-31";
            String endTime = "2020-1-1";
            List<Post> posts = postService.selectByPostTime(startTime,endTime);
            return posts;
        }else {
            return null;
        }
    }




    @RequestMapping("updatePost")
    @ResponseBody
    public String updatePost(Post post){
        Integer postId = post.getPostId();
        Integer rows = postService.updatePost(postId,post);
        if (rows > 0){
            return "success";
        }else {
            return "fail";
        }
    }


    @RequestMapping("updateStatusToZero")
    @ResponseBody
    public String updateStatusToZero(String postId){
        Integer Id = Integer.valueOf(postId);
        Integer rows = postService.updateStatusToZero(Id);
        if (rows > 0){
            return "success";
        }else {
            return "fail";
        }
    }

    @RequestMapping("updateStatusToOne")
    @ResponseBody
    public String updateStatusToOne(String postId){
        Integer Id = Integer.valueOf(postId);
        Integer rows = postService.updateStatusToOne(Id);
        if (rows > 0){
            return "success";
        }else {
            return "fail";
        }
    }



    @RequestMapping("deletePost")
    @ResponseBody
    public String deletePost(Integer postId){
        List<Post> posts = postService.selectByPostId(postId);
        String userName = posts.get(0).getUserName();
        Integer rows = postService.deletePost(postId);
        if (rows > 0){
            // 查出删除的帖子删除其收藏表信息
            Integer row = praiseService.deletePraiseByPostId(postId);
            Integer row1 = userCenterService.updateStatusDel(userName);
                return "success";
        }else {
            return "fail";
        }

    }

    @RequestMapping("deleteByPostTestId")
    @ResponseBody
    public String deleteByPostTestId(Integer postId){
        Integer rows = postTestService.deleteByPostTestId(postId);
        if (rows > 0){
            return "success";
        }else {
            return "fail";
        }

    }

    @RequestMapping("insertPost")
    @ResponseBody
    public String insertPost(Post post){
        Integer rows = postService.insertPost(post);
        if (rows > 0){
            // 若是帖子添加成功则添加同样的收藏表
//            Post post1 = postService.selectPostByPostName(post.getPostName());
//            Praise praise = new Praise();
//            praise.setPostId(post1.getPostId());
//            praise.setPraiseLike(0);
//            praise.setPraiseCollect(0);
//            Integer row = praiseService.insertPraise(praise);
//            if (row > 0){
//                return "success";
//            }else {
//                return "fail";
//            }
            return "success";

        }else {
            return "fail";
        }

    }

    @RequestMapping("insertPostTest")
    @ResponseBody
    public String insertPostTest(String postName, String postType, String postContent, String userName,String other1,MultipartFile photo){
//        System.out.println(session.getAttribute("userId"));
//        System.out.println(session.getAttribute("userinfo"));
//        User user = (User) session.getAttribute("user");
//        String userName = "华华";
//        String userName = user.getUserName();
//        System.out.println("用户名" + userName);
        System.out.println(userName);
        String fileName = photo.getOriginalFilename();
        System.out.println(fileName);
        // 获取文件类型   fileName ->用唯一的值
        //  UUID.randomUUID() + 用户名 + 后缀
        String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
//        System.out.println(fileName);
//        String path = "D:\\upload";
        File dest = new File(name);
//        System.out.println(dest);
        try {
            photo.transferTo(dest);// 完成文件上传到指定目录
        } catch (Exception e ) {
            e.printStackTrace();
        }
        Date date = new Date();
        Posttest posttest = new Posttest();
//        http://localhost:8888/forum/
        String postImg = "http://localhost:8080/img/" + name;
        posttest.setPostName(postName);
        posttest.setPostContent(postContent);
        posttest.setPostPhoto(postImg);
        posttest.setPostType(postType);
        posttest.setUserName(userName);
        posttest.setPostTime(date);

        //取得时间，返回yyyy-MM-dd HH:mm:ss字符串
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time=formatter.format(date);
        // 展示的时间
        posttest.setOther2(time);
        // 部分文档内容
        posttest.setOther1(other1);

        Integer rows = postTestService.insertPost(posttest);
        if (rows > 0){
            return "success";
        }else {
            return "fail";
        }



//        //获取上传文件名,包含后缀
//        String originalFilename = file.getOriginalFilename();
//        System.out.println("获取上传文件名,包含后缀"+originalFilename);
//        //获取后缀
//        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//        System.out.println("获取后缀"+substring);
//        //保存的文件名
//        String dFileName = UUID.randomUUID()+substring;
//        System.out.println("保存的文件名"+dFileName);
//        //保存路径
//        //springboot 默认情况下只能加载 resource文件夹下静态资源文件
//        String path = "D:\\QMDownload\\file";
//        //生成保存文件
//        File uploadFile = new File(path+dFileName);
//        System.out.println(uploadFile);
//        //将上传文件保存到路径
//        try {
//            file.transferTo(uploadFile);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }




    }

    // 富文本编辑器中图片上传接口
    @RequestMapping("upload")
    @ResponseBody
    public WangEditor uploadFile(@RequestParam("photo") MultipartFile photo){
        String fileName = photo.getOriginalFilename();
        System.out.println(fileName);
        // 获取文件类型   fileName ->用唯一的值
        //  UUID.randomUUID() + 用户名 + 后缀
        fileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        System.out.println(fileName);
//        String path = "D:\\upload";
        File dest = new File(fileName);
        System.out.println(dest);
        try {
            photo.transferTo(dest);// 完成文件上传到指定目录
        } catch (Exception e ) {
            e.printStackTrace();
        }
//        Date date = new Date();
//        Posttest posttest = new Posttest();
//        http://localhost:8888/forum/
        String postImg = "http://localhost:8080/img/" + fileName;
        System.out.println(postImg);
//        posttest.setPostName(postName);
//        posttest.setPostContent(postContent);
//        posttest.setPostPhoto(postImg);
//        posttest.setPostType(postType);
//        posttest.setUserName(userName);
//        posttest.setPostTime(date);

//        Integer rows = postTestService.insertPost(posttest);
//        if (rows > 0){
//            return "success";
//        }else {
//            return "fail";
//        }
        String[] data = { postImg };
        WangEditor we = new WangEditor(data);
        return we;

    }


    // 管理员审核帖子
    @RequestMapping("passPostTest")
    @ResponseBody
    public String passPostTest(Integer postId){
        Posttest posttest = postTestService.selectByPostTestId(postId);
        Post post = new Post();
        post.setPostName(posttest.getPostName());
        post.setUserName(posttest.getUserName());
        post.setPostType(posttest.getPostType());
        post.setPostContent(posttest.getPostContent());
        post.setPostTime(posttest.getPostTime());
        post.setOther1(posttest.getOther1());
        post.setStatus(0);
        post.setPostCel(0);
        post.setOther2(posttest.getOther2());
        Integer rows = postService.insertPost(post);
        if (rows > 0){
            // 插入成功 -》管理员确认了
            Integer row = postTestService.deleteByPostTestId(postId);
            Integer row1 = userCenterService.updateStatusAdd(post.getUserName());
            if (row > 0){
                return "审核通过";
            }else {
                return "插入成功，但删除失败";
            }
        }else {
            return "操作出现问题";
        }

    }


//    // 判断是否为热帖
//    public static Integer Arithmetic(Integer num1,Integer num2){
//        // 4 ->收藏人数   6 ->评论数
//        Integer
//    }


}
